<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      html,
      body {
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
    <script type="module">
      import * as THREE from "three";
      import * as Cannon from "cannon-es";
      import { OrbitControls } from "../node_modules/three/examples/jsm/controls/OrbitControls";
      import { scene, camera, renderer } from "../person-roma/src/universal.js";

      //设置场景背景颜色
      scene.background = new THREE.Color(0xc9d6e7);

      camera.position.set(0, 50, 80);
      camera.lookAt(0, 0, 0);

      //光照
      const ambientLight = new THREE.AmbientLight(0xffffff);
      const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
      directionalLight.position.set(0, 100, 50);
      directionalLight.castShadow = true;
      scene.add(ambientLight, directionalLight);

      //创建物理世界
      const world = new Cannon.World({
        gravity: new Cannon.Vec3(0, -9.8, 0),
      });

      //创建可视化地面
      const ground = new THREE.Mesh(
        new THREE.PlaneGeometry(100, 100),
        new THREE.MeshStandardMaterial({
          color: 0x303030,
          side: THREE.DoubleSide,
        })
      );
      ground.receiveShadow = true;
      ground.rotation.x = -Math.PI / 2;
      scene.add(ground);
      //创建物理地面
      const groundBody = new Cannon.Body({
        mass: 0,
        shape: new Cannon.Plane(),
      });
      groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0); //x轴旋转了90°
      world.addBody(groundBody);

      //创建可视化小球
      const sphere = new THREE.Mesh(
        new THREE.SphereGeometry(10, 32, 32),
        new THREE.MeshStandardMaterial({
          color: 0xff0000,
        })
      );
      sphere.castShadow = true;
      sphere.position.set(0, 40, 0);
      scene.add(sphere);
      //创建物理小球
      const sphereBody = new Cannon.Body({
        mass: 1,
        shape: new Cannon.Sphere(10),
      });
      sphereBody.position.copy(sphere.position);
      world.addBody(sphereBody);

      //更新物理世界
      function updatePhysics() {
        world.step(1 / 60);
        sphere.position.copy(sphereBody.position);
      }

      //轨道控制器
      const controls = new OrbitControls(camera, renderer.domElement);
      controls.enableDamping = true;
      controls.addEventListener("change", () => {});

      //动画帧
      const animate = () => {
        updatePhysics();
        controls.update();
        renderer.render(scene, camera);
        window.requestAnimationFrame(animate);
      };
      animate();
    </script>
  </body>
</html>
